package com.fowo.api.syncAmazon.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.LogisticsOrder;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.service.impl.LogisticsOrderServiceImpl;
import com.fowo.api.service.impl.NavSellOrderServiceImpl;
import com.fowo.api.syncAmazon.api.FbaOutboundApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FbaOutboundServiceImpl {

    @Resource
    private NavSellOrderServiceImpl navSellOrderService;
    @Resource
    private FbaOutboundApiService fbaOutboundApiService;
    @Resource
    private LogisticsOrderServiceImpl logisticsOrderService;

    /**
     * 更新订单跟踪号
     */
    public void updateOrderDeliveryTrackId() throws Exception {
        final List<LogisticsOrder> logisticsOrderList = logisticsOrderService.list(Wrappers.lambdaQuery(LogisticsOrder.class)
                .eq(LogisticsOrder::getLogisticsOrderStatus, "1"));
        List<Long> orderIds = logisticsOrderList.stream().map(o -> o.getId()).collect(Collectors.toList());

        List<NavSellOrderVo> navSellOrderVos = navSellOrderService.getVoByIdList(orderIds, true);

        for(NavSellOrderVo navSellOrder : navSellOrderVos){
            String deliveryTrackId = fbaOutboundApiService.getFulfillmentOrder(navSellOrder.getShopInfo(),navSellOrder.getOrderId());
            //更新订单跟踪号
            navSellOrder.setDeliveryTrackId(deliveryTrackId);
            navSellOrder.setDeliveryWaybillId(navSellOrder.getOrderId());
            navSellOrder.setStatus("4");

            navSellOrderService.createIssu(navSellOrder);
            //自动标发
            if (StrUtil.equals(navSellOrder.getIssuActRules(), "1")) {   //自动标发 || 不标发
                navSellOrderService.markDelivery(CollUtil.newArrayList(navSellOrder));   // 1:自动标发 2:不标发
            } else if (StrUtil.equals(navSellOrder.getIssuActRules(), "2")) {  //1:自动标发 2:不标发
                navSellOrderService.unMarkDelivery(CollUtil.newArrayList(navSellOrder));
            }
            //更新物流下单信息
//            logisticsOrderService.update(Wrappers.lambdaUpdate(LogisticsOrder.class)
//                    .set(LogisticsOrder::getLogisticsOrderStatus,"2")
//                    .set(LogisticsOrder::getDeliveryTrackId,deliveryTrackId)
//                    .eq(LogisticsOrder::getOrderId, navSellOrder.getOrderId())
//                    .eq(LogisticsOrder::getLogisticsOrderStatus, "1"));
        }
    }
}
